#!/usr/bin/env python
#Copyright (c) 2011 Isaac Dawson (WBTS Project)
#Permission is hereby granted, free of charge, to any person obtaining a copy 
#of this software and associated documentation files (the "Software"), to deal 
#in the Software without restriction, including without limitation the rights 
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
#THE SOFTWARE.
import cStringIO

class XMLDict():
    """
    I hate myself for even implementing this, but i couldn't find anything
    simple / didn't rely on crazy xml libraries.
    """
    def __init__(self):
        self.mVersion = "<?xml version=\"1.0\"?>\n"
        self.mHeader = "<wbts_results>\n"
        self.mFooter = "\n</wbts_results>\n"
        self.mData = cStringIO.StringIO()
        self._writeHeader()
    
    def _writeHeader(self):
        self.mData.write(self.mVersion)
        self.mData.write(self.mHeader)
    
    def _writeFooter(self):
        self.mData.write(self.mFooter)
        
    def dictToXMLFragment(self, dict, iter, is_cdata=True):
        self.mData.write("\t<result id=\"%d\">\n"%iter)
        for key,value in dict.items():
            # can't be havin nested cdata sections...
            value = value.replace("<![CDATA[", "&lt;![CDATA[")
            value = value.replace("]]>","]]&gt;")
            if(is_cdata == False):
                self.mData.write("\t\t<%s>%s</%s>\n"%(key,value,key))
            else:
                self.mData.write("\t\t<%s><![CDATA[%s]]></%s>\n"%(key,value,key))
        self.mData.write("\t</result>\n")
        return
    
    def toString(self):
        self._writeFooter()
        return self.mData.getvalue()

    def close(self):
        self.mData.close()
